package h0901;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 移动0
 * @date 2024/9/1 22:28
 */
public class MoveZeros {
    public static void main(String[] args) {
        int[] nums = {1,1,0,3,12};
        move2(nums);
        System.out.println(Arrays.toString(nums));
    }

    public static void moveZeroes(int[] nums) {
        LinkedList<Integer> zeros = new LinkedList<>();

        int m = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                zeros.addLast(i);
            } else if (!zeros.isEmpty()){
                int tmp=zeros.removeFirst();
                swap(nums, tmp, i);
                i--;
            }
        }
    }

    private static void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }

    private static void move(int[] nums){
        if(nums==null) {
            return;
        }
        //两个指针i和j
        int j = 0;
        for(int i=0;i<nums.length;i++) {
            //当前元素!=0，就把其交换到左边，等于0的交换到右边
            if(nums[i]!=0) {
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j++] = tmp;
            }
        }
    }
    private static void move2(int[] nums){
        if(nums==null) {
            return;
        }
        //计算出来非0数的个数，然后依次复制
        int m=0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i]!=0){
                m++;
            }
        }
        if (m==0) return;
        int j=0;
        for(int i=0;i< nums.length;i++) {
            //当前元素!=0，就把其交换到左边，等于0的交换到右边
            if (nums[i]!=0){
                nums[j]=nums[i];
                j++;
            }
        }
        for (int i = m; i < nums.length; i++) {
            nums[i]=0;
        }
    }
}
